package com.zhiyun.service.impl;

import com.zhiyun.domain.QuestionType;
import com.zhiyun.mapper.QuestionTypeMapper;
import com.zhiyun.service.QuestionTypeService;
import com.zhiyun.util.Db;
import com.zhiyun.vo.Result;

import java.util.List;

/**
 * @author zc
 * @Date 2025/5/6 下午5:34
 */
public class QuestionTypeServiceImpl implements QuestionTypeService {
    QuestionTypeMapper questionTypeMapper = Db.getMapper(QuestionTypeMapper.class);

    @Override
    public Result findAllQuestionType() {
        List<QuestionType> questionTypes = questionTypeMapper.selectAll();
        return Result.ok(questionTypes);
    }

    @Override
    public Result insertQuestionType(QuestionType questionType) {
        QuestionType oldQuestionType = questionTypeMapper.selectByName(questionType.getName());
        if (oldQuestionType != null) {
            return Result.fail("该类型已存在");
        }
        int rows = questionTypeMapper.insert(questionType);
        if (rows > 0) {
            return Result.okMsg("添加成功");
        }
        return Result.fail("添加失败");
    }

    @Override
    public Result delQuestionType(int questionTypeId) {
        QuestionType questionType = questionTypeMapper.selectByPrimaryKey(questionTypeId);
        if (questionType == null) {
            return Result.fail("类型不存在");
        }
        int rows = questionTypeMapper.deleteByPrimaryKey(questionTypeId);
        if (rows > 0) {
            return Result.okMsg("删除成功");
        }
        return Result.fail("删除失败");
    }

    @Override
    public Result updateQuestionType(QuestionType questionType) {
        QuestionType oldQuestionType = questionTypeMapper.selectByPrimaryKey(questionType.getId());
        if (oldQuestionType == null) {
            return Result.fail("要修改的类型不存在");
        }
        if (!questionType.getName().equals(oldQuestionType.getName())) {
            QuestionType questionType1 = questionTypeMapper.selectByName(questionType.getName());
            if (questionType1 != null) {
                return Result.okMsg("该类型已存在");
            }
        }
        int rows = questionTypeMapper.updateByPrimaryKey(questionType);
        if (rows > 0) {
            return Result.okMsg("修改成功");
        }
        return Result.fail("修改失败");
    }
}
